package com.example.administrator.myapplication;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class SecendActivity extends AppCompatActivity {
    //注册局部广播  数据只会在本应用程序里面传输，也只能接收本应用程序发送过来的广播，相比全局广播，更安全，更高效
    private BroadcastReceiver mBroadcastReceiver;
    private LocalBroadcastManager mBroadCastManager;
    private TextView mTvText;
    private Thread mThread;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_secend);
        mTvText = (TextView) findViewById(R.id.tv_text);

    }

    @Override
    protected void onResume() {
        super.onResume();
        //得到局部广播管理类的实例
        mBroadCastManager = LocalBroadcastManager.getInstance(this);
        IntentFilter iFilter = new IntentFilter();
        iFilter.addAction("com.go");
        mBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String msg = intent.getStringExtra("msg");
                mTvText.setText(msg);
            }
        };
        mBroadCastManager.registerReceiver(mBroadcastReceiver,iFilter);
        mThread = new Thread(new MyThread());
        mThread.start();
    }
    //解除注册
    @Override
    protected void onPause() {
        super.onPause();
        mBroadCastManager.unregisterReceiver(mBroadcastReceiver);
        mThread.interrupt();
    }

    class MyThread implements Runnable{

        @Override
        public void run() {
            for (int i = 0; i < 100 ; i++) {
                Intent intent = new Intent("com.go");
                intent.putExtra("msg",""+i);
                mBroadCastManager.sendBroadcast(intent);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
